<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row :gutter="22">
          <el-col :span="10">
            <el-input placeholder="请输入内容" v-model="getquery.query" class="input-with-select" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList" ></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name"  label="角色"></el-table-column>
        <el-table-column  label="状态">
          <template slot-scope="scope">
                <el-switch v-model="scope.row.mg_state" @change="getuserstatus(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="编辑" placement="top" :enterable="false">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row.id)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                  <el-button type="warning" icon="el-icon-share" size="mini" @click="fpjues(scope.row)"></el-button>
                </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

<!--     分页功能-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getquery.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="getquery.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
<!--    对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%">
<!--      主内容-->
      <el-form :model="userdateform" :rules="formrules" ref="ruleForm" label-width="70px" @close="removeform">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userdateform.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userdateform.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userdateform.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userdateform.mobile"></el-input>
        </el-form-item>
      </el-form>


      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>


<!--    编辑-->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editdialogVisible"
      width="50%">


      <el-form :model="editdate" :rules="formrules" ref="ruleFormEdit" label-width="70px" @close="removeform">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editdate.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editdate.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editdate.mobile"></el-input>
        </el-form-item>
      </el-form>


      <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="edituser">确 定</el-button>
  </span>
    </el-dialog>

<!--    分配权限-->
    <el-dialog
      title="分配角色"
      :visible.sync="fpdialogVisible"
      width="50%">
      <p>当前的用户:{{this.fpuserlist.username}}</p>
      <p>当前的角色:{{this.fpuserlist.role_name}}</p>
      <p>分配新角色:
        <el-select v-model="selectrole" placeholder="请选择">
          <el-option
            v-for="item in jueslist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
    <el-button @click="fpdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitrole">确 定</el-button>
  </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
      data() {
        var checkEmail = (rule,value,callback) => {
          const reg = /[a-zA-Z0-9]{1,10}@[a-zA-Z0-9]{1,5}\.[a-zA-Z0-9]{1,5}/
          if (reg.test(value)) {
            return callback()
          }
          callback(new Error('邮箱格式不对'))
        };
        var checkMobile = (rule,value,callback) => {
          const reg = /^1[0-9]{10}/
          if (reg.test(value)) {
            return callback()
          }
          callback(new Error('手机号格式不对'))
        };
          return {
            getquery: {
              query: '',
              pagenum: 1,
              pagesize: 2
            },
            userlist: [],
            total: 0,
            dialogVisible: false,
            editdialogVisible: false,
            userdateform: {
              username: '',
              password: '',
              email: '',
              mobile: ''
            },
            editdate: {
              id: '',
              username: '',
              email: '',
              mobile: ''
            },
            formrules: {
              username: [
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
              ],
              password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
              ],
              email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                { min: 5, message: '长度在 6 到 12 个字符', trigger: 'blur' },
                { validator: checkEmail, trigger: 'blur' }
              ],
              mobile: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
                { validator: checkMobile, trigger: 'blur' }
              ]
            },
            fpdialogVisible: false,
            // 用户信息
            fpuserlist: {},
            jueslist: [],
            selectrole: ''
          }

      },
      created() {
        this.getUserList()
      },
      methods: {
        async getUserList() {
          const {data: res} = await this.$http.get('users',{params: this.getquery})
          if (res.meta.status !== 200) return this.$message.error(res.meta.message)
          this.userlist = res.data.users
          this.total = res.data.total
        },
        handleSizeChange(size) {
          this.getquery.pagesize = size
          this.getUserList()
        },
        handleCurrentChange(size) {
          this.getquery.pagenum = size
          this.getUserList()
        },
        async getuserstatus(data) {
          const {data: res} = await this.$http.put(`users/${data.id}/state/${data.mg_state}`)
          if (res.meta.status !== 200) return this.$message.error(res.meta.message)
          this.$message.success('更新用户状态成功')
        },
        removeform() {
            this.$refs.ruleForm.resetFields()
        },
        addUser() {
          this.$refs.ruleForm.validate(async  valid => {
            if (!valid) return this.$message.error('表单验证失败')
            const {data: res} = await this.$http.post('users',this.userdateform)
            if(res.meta.status !== 201) return this.$message.error(res.meta.message)
            this.$message.success('添加用户成功')
            this.dialogVisible = false
            this.getUserList()
           })
        },
        async edit(id) {
          this.id =
          this.editdialogVisible = true
          const {data: res} = await this.$http.get(`users/${id}`)
          if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
          this.editdate.username = res.data.username
          this.editdate.mobile = res.data.mobile
          this.editdate.email = res.data.email
          this.editdate.id =  res.data.id
        },
        edituser() {
          this.$refs.ruleFormEdit.validate(async valid => {
            if (!valid) return this.$message.error('表单验证失败')
            const {data: res} = await this.$http.put(`users/${this.editdate.id}`,this.editdate)
            if (res.meta.status !== 200) return this.$message.error('修改失败')
            this.$message.success('修改成功')
            this.editdialogVisible = false
            this.getUserList()
          })
        },
        async deleteUser(id) {
          const reults = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
          if (reults !== 'confirm') {
            return false
          }
          const {data: res} = await this.$http.delete(`users/${id}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.getUserList()
          this.$message.success('删除成功')
        },
        async fpjues(info) {
          this.fpdialogVisible = !this.fpdialogVisible
          this.fpuserlist = info
          const {data: res}  = await this.$http.get('roles')
          if (res.meta.status !== 200) return this.$message.error('获取角色失败')
          this.jueslist = res.data
        },
        async submitrole() {
          this.fpdialogVisible = !this.fpdialogVisible
          if (!this.selectrole) {
            return this.$message.error('请选择要分配的角色')
          }
          const {data: res} = await this.$http.put(`users/${this.fpuserlist.id}/role`,{rid: this.selectrole})
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error('更新角色失败')
          this.$message.success('更新角色成功')
          this.getUserList()
        }
      }
}
</script>

<style scoped>
.el-breadcrumb {
  margin: 0 0 15px 15px;
}
.el-pagination {
  margin-top: 10px;
}
</style>
